<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="params.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handerinput" />
        <!-- 树形组件 -->
        <el-tree ref="myref" node-key="id" :data="treeData" :props="{label:'name'}" default-expand-all :highlight-current="true" :expand-on-click-node="false" @node-click="nodeClick" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="ExcleClick">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tabledata">
          <el-table-column label="头像" align="center" prop="staffPhoto">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username[0] }}</span>
            </template>
          </el-table-column>

          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ row.formOfEmployment ===1 ? '正式': row.formOfEmployment === 2 ? '非正式' : '无' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="DisplayDialog(row.id)">角色</el-button>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                @onConfirm="onConfirm(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="params.page"
          :page-sizes="[1, 2, 3, 5]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <import-excel :show-excel-dialog.sync="showExcelDialog" @reload="getRmployee" /></div>
    <!-- 角色弹窗 -->
    <el-dialog :visible.sync="visible">
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in roles"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>

      </el-checkbox-group>
      <div>
        <el-button type="primary" size="mini">确认</el-button>
        <el-button size="mini" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetDepts } from '@/api/department'
import { translateTreeData } from '@/utils/index'
import { reqGetemp, reqExoirtExcel, reqdelTmp, reqRoleEnvled, reqPutXg } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'

export default {

  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      treeData: [],
      params: {
        departmentId: null,
        pagesize: 5,
        page: 1,
        keyword: ''

      },
      total: 0,
      tabledata: [],
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      visible: false,
      roles: [],
      checkList: []
    }
  },
  created() {
    this.getDopts()
  }, methods: {
    async   getDopts() {
      const { data } = await reqGetDepts()
      console.log({ data })
      this.treeData = translateTreeData(data, 0)
      // 存一个值放id 放默认id
      this.params.departmentId = this.treeData[0].id
      // 给dom节点设置时这块是异步的
      await this.$nextTick()
      // 调用这个方法设置
      this.$refs.myref.setCurrentKey(this.params.departmentId)
      this.getRmployee()
      //
    },
    // 叶子被点击
    nodeClick(data) {
      // console.log(data)
      // 绑定点击事件记录点击的id
      this.params.departmentId = data.id
      // 后用到切换时要让页面回到第一页
      this.params.page = 1
      this.getRmployee()
    },
    // 获取员工列表
    async  getRmployee() {
      const { data: { rows, total }} = await reqGetemp(this.params)
      // console.log(rows)  总数存起来
      this.total = total
      // 一个数组存起来 渲染table
      this.tabledata = rows
      console.log(this.tabledata)
    },
    handleSizeChange(val) {
      // 每页条数发生变化
      this.params.pagesize = val
      this.getDopts()
    },
    handleCurrentChange(val) {
      // 页面
      this.params.page = val
      this.getDopts()
    },
    handerinput() {
      this.params.page = 1
      if (!this.params.keyword.trim()) return
      clearTimeout(this.trmer)
      this.trmer = setTimeout(async() => {
        await this.getRmployee()
      }, 500)
    },
    async  ExcleClick() {
      // console.log(1)
      const blob = await reqExoirtExcel()
      FileSaver.saveAs(blob, '员工表格')
    },
    // 删除
    async onConfirm(id) {
      if (this.treeData.length === 1 && this.params.page > 1) return this.params.page--
      this.getRmployee()
      await reqdelTmp(id)
    },
    // 角色
    DisplayDialog(id) {
      console.log(1)
      this.visible = true
      this.showAssign(id)
    },
    // 获取已启用的
    async showAssign(id) {
      // const res = await reqRoleEnvled()
      // this.roles = res.data
      // await reqPutXg(id)
      // 发生2个请求做优化
      Promise.all([reqRoleEnvled(), reqPutXg(id)]).then(values => {
        this.roles = values[0].data
        this.checkList = values[1].data.roleIds
        this.visible = true
      })
    }

  }

}

</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
